package edu.mbb.mybatis;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import edu.mbb.core.Configuration;

public class MyBaseExecutor implements MyExecutor {

	@Override
	public <T> T query(String sql, Class<?> returnType, String methodName) throws SQLException {

		Connection connection = DataSourceFactory.getConnection();
		// sql = replaceSql(sql);
		ReentrantLock lock = new ReentrantLock();
		lock.lock();
		PreparedStatement prepareStatement = connection.prepareStatement(sql);
		List<String> xmlArgs = Configuration.getXmlArgs(methodName);
		if (xmlArgs.size() > 0) {
			for (int i = 0; i < xmlArgs.size(); i++) {
				prepareStatement.setObject(i + 1, Configuration.getArgsValues(xmlArgs.get(i)));
			}
		}
		ResultSet resultSet = prepareStatement.executeQuery();

		Object instance = null;
		try {

			if (resultSet.next()) {
				instance = returnType.newInstance();
				Field[] fields = returnType.getDeclaredFields();
				for (Field field : fields) {
					field.setAccessible(true);
					field.set(instance, resultSet.getObject(field.getName()));
				}
			}
			// 使用完成 清空数据

			Configuration.cleanData();
			return (T) instance;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			lock.unlock();
			if (resultSet != null) {
				resultSet.close();
			}
			if (prepareStatement != null) {
				prepareStatement.close();
			}
			if (connection != null) {
				connection.close();
			}
		}
	}

}
